package com.king.security.security;

import com.king.security.entity.MyUser;
import com.king.security.repository.UserRepository;
import lombok.Getter;
import lombok.Setter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.ArrayList;
import java.util.List;

/**
 * 需要实现UserDetailsService接口
 * 因为在Spring Security中我们配置相关参数需要UserDetailsService类型的数据
 * @author KING
 * @date 2018/8/30 22:25
 */
@Getter
@Setter
public class JwtUserDetailsServiceImpl implements UserDetailsService {

    /**
     * 注入持久层对象UserRepository
     */
    protected UserRepository userRepository;

    /**
     * 实现接口中的loadUserByUsername方法，通过该方法查询到对应的用户
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 调用持久层接口findByLoginName方法查找用户，此处的传进来的参数实际是loginName
        MyUser fkUser = userRepository.findByUserName(username);
        if (fkUser == null) {
            throw new UsernameNotFoundException("用户名不存在");
        }
        // 创建List集合，用来保存用户权限，GrantedAuthority对象代表赋予给当前用户的权限
        List<GrantedAuthority> authorities = new ArrayList<>();

        // 此处返回的是org.springframework.security.core.userdetails.User类，该类是Spring Security内部的实现
        return new User(fkUser.getUserName(), fkUser.getPassword(), authorities);
    }

}
